/*
 * @desc 路由控制
 * */
define(['classer', 'histery'], function(classer, histery){
	var win = window,
		//hash分隔符
		hashTag = '#';

    var Router = classer.extend({
	    init : function(options){
			this.on(options);
	    },

        //路由绑定
        on : function(path, listener){
            if(typeof path === 'object'){
                for(var i in path){
	                this._bind(i, path[i]);
                }
            }else{
	            this._bind(path, listener);
            }
            return this;
        },

	    //路由绑定
	    _bind : function (path, listener){
			this._routeList.push(new Route({
				path : path,
				listener : listener,
				separate : this.settings.separate
			}));
		},

        //开始监听
        start : function(){
	    	var me = this;
	        histery.onhashchange(function(){
		        me.dispatch();
	        });
	        me.dispatch();
        },

        //跳转指定路由
        redirect : function(path){
            histery.pushState({}, '', this.buildUrl(path));
            this.dispatch();
        },

        //返回
        back : function(){
            histery.back();
        },

	    //链接返回，不执行监控方法
	    backoff : function() {
        	this._unCheck = true;
		    histery.back();
	    },

        //设置配置
        sets : function(options){
            options = options || {}, opts = {};
            for(var i in this.settings){
                if(typeof options[i] !== 'undefined' && options[i] !== null) this.settings[i] = options[i];
            }
        },

	    //检测状态
	    checkPath : function (){
			var path;
			if(this.settings.hash){
				path = win.location.hash.replace(hashTag + this.settings.separate, '');
			}else{
				path = win.location.search.replace(/^\?/, '');
			}
			if(path !== this._activePath && path !== null){
				this._activePath = path;
				return path;
			}
			return false;
		},

		//路由检测
	    dispatch : function (){
			var path, route, adapter;
			path = this.checkPath();
			if(path === false) return;
			//是否需要检测匹配监控
			if(this._unCheck === true){
				this._unCheck = false;
				return;
			}
			for(var i = 0; i < this._routeList.length; i++){
				if(this._routeList[i].adapter(path)){
					adapter = this._routeList[i];
				}
				if(this._routeList[i].match(path)){
					route = this._routeList[i];
					break;
				}
			}
			if(route){
				route.listener.apply(route, route.getParams());
			}else if(adapter){
				adapter.listener.apply(adapter);
			}
		},

		//生成完整地址
	    buildUrl : function (path){
			var prePath, url;
			if(this.settings.hash){
				prePath = this.settings.root + this.settings.search;
				prePath = prePath.split(hashTag + this.settings.separate)[0];
				url = prePath + hashTag + this.settings.separate + path;
			}else{
				prePath = this.settings.root;
				url = prePath + '?' + path;
			}
			return url;
		},

		_activePath : null,

	    //配置
	    settings : {
		    //是否使用hash模式
		    hash : true,
		    //分隔符
		    separate : '!',
		    //相对地址
		    root : (win.location.href.split(hashTag + this.separate)[0]).split('?')[0],
		    //搜索地址
		    search : win.location.search
	    },

	    //路由列表
	    _routeList : []//[{path : '', listener : function(){}}]
    });

    //路由类
    function Route(){
        this.init.apply(this, arguments);
    }

    Route.prototype = {
        separate : '!',

        //初始化
        init : function(options){
            this.path = options.path || '*';
            this.listener = options.listener || function(){};
            this.separate = options.separate || this.separate;
        },

        //获取路径参数
        getParams : function(){
            if(!this.params) this.params = [];
            return this.params;
        },

        //路径匹配
        match : function(path){
            var b = false, myPath = this.path, reg;
            this.params = [];
            myPath = myPath.replace('*', '\*').replace('?', '\?').replace('+', '\+').replace('.', '\.');
            if(/:/.test(myPath)){
                myPath = myPath.replace(/\:\w|\w\:/ig, '(.*)');
                reg = new RegExp('^' + myPath + '$');
                b = reg.test(path);
                if(b){
                    var params = reg.exec(path), arr = [];
                    for(var i = 1; i < params.length; i++){
                        arr.push(params[i]);
                    }
                    this.params = arr;
                }
            }else{
                b = myPath === path;
            }

            return b;
        },

        //路径适配
        adapter : function(){
            var b = false;
            if(this.path === '*') b = true;
            return b;
        }
    };

    return Router;
});